package com.dongdongshop.controller;

import com.dongdongshop.data.Result;
import com.dongdongshop.enums.ResultEnum;
import com.dongdongshop.service.CartService;
import com.dongdongshop.util.JwtUtil;
import com.dongdongshop.vo.CartVO;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("cart")
public class CartController {


    @Autowired
    private CartService cartService;
    @Autowired
    private JwtUtil jwtUtil;

    /*
     * itemId :商品skuId
     * num : 购买的数量
     *AutharizeToken :获取商家Id
     * */
    @PostMapping("addCart")
    public Result addCart(@RequestHeader String AutharizeToken, @RequestParam Integer num, @RequestParam Long itemId) {
        String userId = "";
        try {
            Claims claims = jwtUtil.parseJwt(AutharizeToken);
            userId = claims.getId();//登陆用户的id
        } catch (Exception e) {
            e.printStackTrace();
            return Result.RESPOSE(ResultEnum.INVALID_TOKEN);
        }
        try {
            cartService.addCart(userId, num, itemId);
        } catch (Exception e) {
            return Result.FAIL();
        }
        return Result.OK();
    }

    @GetMapping("getCart")
    public Result getCart(@RequestHeader String AutharizeToken) {
        String userId = "";
        try {
            Claims claims = jwtUtil.parseJwt(AutharizeToken);
            userId = claims.getId();//登陆用户的id
        } catch (Exception e) {
            e.printStackTrace();
            return Result.RESPOSE(ResultEnum.INVALID_TOKEN);
        }
        List<CartVO> list = cartService.getCartVOListFromRedis(userId);
        return Result.OK().setData(list);
    }

    @PostMapping("deleteCart")
    public Result deleteCart(@RequestHeader String AutharizeToken) {
        String userId = "";
        try {
            Claims claims = jwtUtil.parseJwt(AutharizeToken);
            userId = claims.getId();//登陆用户的id
        } catch (Exception e) {
            e.printStackTrace();
            return Result.RESPOSE(ResultEnum.INVALID_TOKEN);
        }
        cartService.deleteCart(userId);
        return Result.OK();
    }
}
